
import React, { useState } from 'react';
import { 
  Box,
  Grid,
  TextField,
  Button,
  Stack,
  Typography,
  Paper,
  Divider
} from '@mui/material';
import io from 'socket.io-client';

import { Await } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { login } from '../api/user';
import { register } from '../api/user';
import { getRigisterCode } from '../api/user';
import { changePassword } from '../api/user';

import { 
  getCommunityPosts, 
  getPostById, 
  createPost, 
  searchPosts, 
  getHotTags, 
  getCommunityAnnouncements, 
  getFeaturedPosts, 
  likePost, 
  unlikePost, 
  getPostComments, 
  createComment, 
  getUserPosts 
} from '../api/community';

// 添加测试账号数据
const TEST_USER = {
  email: 'test@example.com',
  password: '123456',
  id: 'test-user-id'
};

const AuthPage = () => {
  const [authType, setAuthType] = useState('login'); // 'login' 或 'register'
  const [loginType, setLoginType] = useState('password'); // 'password' 或 'email'
  const [id,setId] = useState(0);
  const [showAppeal, setShowAppeal] = useState(false);
const [appealText, setAppealText] = useState("");
const socket = io('http://localhost:5000'); // 根据后端地址修改

function showAppealForm() {
  setShowAppeal(true);
}
  const [codeSent, setCodeSent] = useState(false);   // 是否发送过验证码
  const [sending, setSending] = useState(false);     // 发送中状态
  const [verifyMsg, setVerifyMsg] = useState('');    // 验证结果消息
  // 登录表单状态
  const [loginCredentials, setLoginCredentials] = useState({
    account: '',
    password: '',
    email: '',
  });
  const [forgotPassword, setForgotPassword] = useState(false);
  const [forgotForm, setForgotForm] = useState({
    email: '',
    code: '',
    password: ''
  });
const [sendingReset, setSendingReset] = useState(false);

  // 注册表单状态
  const [registerForm, setRegisterForm] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    invitationCode: '',
    code: ''
  });
  const navigate = useNavigate()

async function handleLoginSubmit(e) {
  e.preventDefault();

  const credentials = loginType === 'password'
    ? { email: loginCredentials.account, password: loginCredentials.password }
    : { email: loginCredentials.email, password: loginCredentials.password };

  // 先检查是否匹配测试账号
  if ((credentials.email === TEST_USER.email && credentials.password === TEST_USER.password) ||
      (loginCredentials.account === TEST_USER.email && credentials.password === TEST_USER.password)) {
    // 模拟登录成功
    localStorage.setItem("token", "test-token");
    localStorage.setItem("user", TEST_USER.id);
    localStorage.setItem("id", TEST_USER.id);
    alert('测试账号登录成功！');
    navigate('/');
    return;
  }

  try {
    console.log("发送的登录参数：", credentials);

    const res = await login(credentials);
    console.log(res);
    if (res.message === '账户已被封禁') {
      // 弹出申诉表单
          console.log(res.message);
              setId(res.id);
      showAppealForm(); // 你需要实现这个函数展示表单
    } else if (res.message && res.token) {
      localStorage.setItem("token", res.token);
      localStorage.setItem("user", res.id);
      localStorage.setItem("id", res.id);
      navigate('/');
    } else {
      alert('登录失败！');
    }
  } catch (err) {
    console.error('登录失败:', err);
    const message = err.response?.data?.message || '网络错误或服务器异常！';
    alert(`登录失败：${message}`);
  }
}

const sendCode = async () => {
    if (!registerForm.email) {
      alert('请输入邮箱！');
      return;
    }
    setSending(true);
    try {
      const res = await getRigisterCode(registerForm.email);
      alert(res.msg || '验证码已发送');
      setCodeSent(true);
    } catch (error) {
      alert('发送失败，请稍后重试');
      console.error(error);
    } finally {
      setSending(false);
    }
  };
const sendResetCode = async () => {
  if (!forgotForm.email) {
      alert('请输入邮箱！');
      return;
    }
    setSending(true);
    try {
      const res = await getRigisterCode(forgotForm.email);
      alert(res.msg || '验证码已发送');
      setCodeSent(true);
    } catch (error) {
      alert('发送失败，请稍后重试');
      console.error(error);
    } finally {
      setSending(false);
    }
};
  async function handleAppealSubmit() {
  try {
    if (appealText.trim()) {
      const message = {
        sender_id: id,
        receiver_id: 1,
        content: `来自被封禁用户(id:${id})的申诉：`+ appealText
      };
      socket.emit('send_message', message);
    }
    alert("申诉已提交！");
    setShowAppeal(false);
    setAppealText("");
  } catch (error) {
    alert("申诉提交失败，请稍后再试！");
  }
}
  const handleRegisterSubmit = async (e) => {
  e.preventDefault();

  const { username, email, password, confirmPassword, invitationCode,code } = registerForm;

  // 前端检查：密码是否一致
  if (password !== confirmPassword) {
    alert('两次输入的密码不一致！');
    return;
  }

  try {
    const res = await register({
      username,
      email,
      password,
      code,
      invitationCode
    });
    console.log("响应内容：", res.message);

    if (res.message) {
      localStorage.setItem("first_time", "true");
      alert('注册成功！请登录');
      setAuthType('login');
    } else {
      alert(`注册失败：${res.message || '未知错误'}`);
    }
  } catch (err) {
    console.error('注册失败:', err);
    const message = err.response?.message || '网络错误或服务器异常！';
    alert(`注册失败：${message}`);
  }
};
const handleResetPasswordSubmit = async (e) => {
  e.preventDefault();

  const {  email, password,  code } = forgotForm;


  try {
    const res = await changePassword({
      email,
      password,
      code,
    });
    console.log("响应内容：", res.msg);

    if (res.msg) {
      alert('修改成功！请登录');
      setAuthType('login');
    } else {
      alert(`修改失败：${res.data.message || '未知错误'}`);
    }
  } catch (err) {
    console.error('修改失败:', err);
    const message = err.response?.data?.message || '网络错误或服务器异常！';
    alert(`修改失败：${message}`);
  }
};
  const handleInputChange = (e, formType) => {
    const { name, value } = e.target;
    if (formType === 'login') {
      setLoginCredentials(prev => ({ ...prev, [name]: value }));
    } else if (formType === 'reset') {
    setForgotForm(prev => ({ ...prev, [name]: value }));
  }else{
      setRegisterForm(prev => ({ ...prev, [name]: value }));
    }
  };

  const switchLoginType = (type) => {
    setLoginType(type);
    setLoginCredentials({
      account: '',
      password: '',
      email: '',
    });
  };

  return (
    <Box
      sx={{
        display: 'flex',
        minHeight: '100vh',
        alignItems: 'center',
        justifyContent: 'center',
        bgcolor: '#f5f5f5',
        p: 2
      }}
    >
      <Paper
        elevation={6}
        sx={{
          width: '80%',
          maxWidth: 1100,
          height: '70%',
          borderRadius: 4,
          overflow: 'hidden'
        }}
      >
        <Grid container sx={{ height: '100%' }}>
          {/* 左侧欢迎区域 */}
          <Grid item xs={12} md={6}>
            <Box
              sx={{
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                background: 'linear-gradient(135deg, #1976d2 0%, #2196f3 100%)',
                color: 'white',
                p: 4,
                width:520,
                textAlign: 'center'
              }}
            >
              <Typography variant="h3" component="h1" sx={{ fontWeight: 'bold', mb: 3 }}>
                欢迎回来!
              </Typography>
              <Typography variant="h6" sx={{ mb: 4, maxWidth: 400 }}>
                {authType === 'login' 
                  ? '加入我们的社区，发现更多精彩内容' 
                  : '创建您的账户，开始您的旅程'}
              </Typography>
              
              {authType === 'login' && (
                <Button 
                  variant="contained" 
                  size="large"
                  sx={{
                    bgcolor: 'white',
                    color: '#1976d2',
                    '&:hover': { bgcolor: '#f5f5f5' },
                    px: 4,
                    py: 1.5,
                    borderRadius: 2,
                    fontWeight: 'bold'
                  }}
                  onClick={() => setAuthType('register')}
                >
                  邀请码注册
                </Button>
              )}
            </Box>
          </Grid>

          {/* 右侧表单区域 */}
          <Grid item xs={12} md={6}>
            <Box
              sx={{
                p: 4,
                height: '100%',
                display: 'flex',
                width: 450,
                flexDirection: 'column',
                justifyContent: 'center',
                bgcolor: 'background.paper'
              }}
            >
              {authType === 'login' ? (
                forgotPassword ? (
                  <>
                    <Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold', mb: 3 }}>
                      重置密码
                    </Typography>

                    <form onSubmit={(e) => handleResetPasswordSubmit(e)}>
                      <Stack spacing={3}>
                        <TextField
                          fullWidth
                          label="邮箱"
                          name="email"
                          type="email"
                          variant="outlined"
                          value={forgotForm.email}
                          onChange={(e) => handleInputChange(e, 'reset')}
                          required
                        />
                        <Stack direction="row" spacing={2}>
                          <TextField
                            fullWidth
                            label="验证码"
                            name="code"
                            variant="outlined"
                            value={forgotForm.code}
                            onChange={(e) => handleInputChange(e, 'reset')}
                            required
                          />
                          <Button
                            variant="outlined"
                            onClick={sendResetCode}
                            disabled={sendingReset || !forgotForm.email}
                          >
                            {sendingReset ? '发送中...' : '发送验证码'}
                          </Button>
                        </Stack>
                        <TextField
                          fullWidth
                          label="新密码"
                          name="password"
                          type="password"
                          variant="outlined"
                          value={forgotForm.password}
                          onChange={(e) => handleInputChange(e, 'reset')}
                          required
                        />
                        <Button
                          fullWidth
                          variant="contained"
                          size="large"
                          type="submit"
                          sx={{ py: 1.5, mt: 2 }}
                        >
                          重置密码
                        </Button>
                        <Button
                          variant="text"
                          size="small"
                          onClick={() => setForgotPassword(false)}
                        >
                          返回登录
                        </Button>
                      </Stack>
                    </form>
                  </>
                ) : (
                  <>
                    <Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold', mb: 3 }}>
                      用户登录
                    </Typography>

                    {/* 登录方式切换 */}
                    <Stack direction="row" spacing={2} sx={{ mb: 4 }}>
                      <Button 
                        fullWidth
                        variant={loginType === 'password' ? 'contained' : 'outlined'}
                        onClick={() => switchLoginType('password')}
                        sx={{ py: 1.5 }}
                      >
                        密码登录
                      </Button>
                      <Button 
                        fullWidth
                        variant={loginType === 'email' ? 'contained' : 'outlined'}
                        onClick={() => switchLoginType('email')}
                        sx={{ py: 1.5 }}
                      >
                        验证码登录
                      </Button>
                    </Stack>

                    {/* 登录表单 */}
                    <form onSubmit={(e) => handleLoginSubmit(e)}>
                      <Stack spacing={3}>
                        {loginType === 'password' ? (
                          <>
                            <TextField
                              fullWidth
                              label="手机号/邮箱"
                              name="account"
                              variant="outlined"
                              value={loginCredentials.account}
                              onChange={(e) => handleInputChange(e, 'login')}
                              required
                            />
                            <TextField
                              fullWidth
                              label="密码"
                              name="password"
                              type="password"
                              variant="outlined"
                              value={loginCredentials.password}
                              onChange={(e) => handleInputChange(e, 'login')}
                              required
                            />
                          </>
                        ) : (
                          <>
                            <TextField
                              fullWidth
                              label="邮箱"
                              name="email"
                              type="email"
                              variant="outlined"
                              value={loginCredentials.email}
                              onChange={(e) => handleInputChange(e, 'login')}
                              required
                            />
                            <TextField
                              fullWidth
                              label="密码"
                              name="password"
                              type="password"
                              variant="outlined"
                              value={loginCredentials.password}
                              onChange={(e) => handleInputChange(e, 'login')}
                              required
                            />
                          </>
                        )}

                        <Button
                          variant="text"
                          size="small"
                          sx={{ mt: 1, alignSelf: 'flex-end' }}
                          onClick={() => setForgotPassword(true)}
                        >
                          忘记密码？
                        </Button>

                        <Button
                          fullWidth
                          variant="contained"
                          size="large"
                          type="submit"
                          sx={{ 
                            py: 1.5, 
                            mt: 2,
                            bgcolor: '#1976d2',
                            '&:hover': { bgcolor: '#1565c0' }
                          }}
                        >
                          登录
                        </Button>
                      </Stack>
                    </form>
                    {showAppeal  && (
                    <div style={{
                      position: 'fixed',
                      top: 0, left: 0,
                      width: '100%',
                      height: '100%',
                      backgroundColor: 'rgba(0,0,0,0.6)',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                      zIndex: 999
                    }}>
                      <div style={{
                        background: '#fff',
                        padding: '20px',
                        borderRadius: '12px',
                        width: '400px',
                        maxWidth: '90%',
                        boxShadow: '0 4px 20px rgba(0,0,0,0.3)'
                      }}>
                        <h3>您的账号已被封禁</h3>
                        <p>如您认为这是误封，请填写申诉内容：</p>
                        <textarea
                          rows="4"
                          style={{ width: '100%', marginTop: '10px' }}
                          value={appealText}
                          onChange={(e) => setAppealText(e.target.value)}
                          placeholder="请输入申诉理由"
                        />
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '15px' }}>
                          <button onClick={handleAppealSubmit}>提交申诉</button>
                          <button onClick={() => setShowAppeal (false)}>关闭</button>
                        </div>
                      </div>
                    </div>
                  )}
                    <Divider sx={{ my: 3 }} />
                  </>
                )
              ) 
              : (
                <>
                  <Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold', mb: 3 }}>
                    用户注册
                  </Typography>
                  
                  {/* 注册表单 */}
                  <form onSubmit={handleRegisterSubmit}>
                    <Stack spacing={3}>
                      <TextField
                        fullWidth
                        label="用户名"
                        name="username"
                        variant="outlined"
                        value={registerForm.username}
                        onChange={(e) => handleInputChange(e, 'register')}
                        required
                      />
                      <TextField
                        fullWidth
                        label="邮箱"
                        name="email"
                        type="email"
                        variant="outlined"
                        value={registerForm.email}
                        onChange={(e) => handleInputChange(e, 'register')}
                        required
                      />
                      <Button
                        variant="contained"
                        onClick={sendCode}
                        disabled={sending || !registerForm.email}
                      >
                        {sending ? '发送中...' : (codeSent ? '重新发送验证码' : '发送验证码')}
                      </Button>

                      {codeSent && (
                        <>
                          <TextField
                            fullWidth
                            label="验证码"
                            name="code"
                            variant="outlined"
                            value={registerForm.code}
                            onChange={(e) => handleInputChange(e, 'register')}
                            required
                          />
                        </>
                      )}
                      <TextField
                        fullWidth
                        label="验证码"
                        name="code"
                        type="code"
                        variant="outlined"
                        value={registerForm.code}
                        onChange={(e) => handleInputChange(e, 'register')}
                        required
                      />
                      <TextField
                        fullWidth
                        label="密码"
                        name="password"
                        type="password"
                        variant="outlined"
                        value={registerForm.password}
                        onChange={(e) => handleInputChange(e, 'register')}
                        required
                      />
                      <TextField
                        fullWidth
                        label="确认密码"
                        name="confirmPassword"
                        type="password"
                        variant="outlined"
                        value={registerForm.confirmPassword}
                        onChange={(e) => handleInputChange(e, 'register')}
                        required
                      />
                      <TextField
                        fullWidth
                        label="邀请码"
                        name="invitationCode"
                        variant="outlined"
                        value={registerForm.invitationCode}
                        onChange={(e) => handleInputChange(e, 'register')}
                        required
                      />

                      <Button
                        fullWidth
                        variant="contained"
                        size="large"
                        type="submit"
                        sx={{ 
                          py: 1.5, 
                          mt: 2,
                          bgcolor: '#1976d2',
                          '&:hover': { bgcolor: '#1565c0' }
                        }}
                      >
                        注册
                      </Button>
                    </Stack>
                  </form>

                  <Divider sx={{ my: 3 }} />

                  <Stack direction="row" justifyContent="center">
                    <Typography variant="body2">
                      已有账号? 
                      <Button 
                        variant="text" 
                        size="small"
                        onClick={() => setAuthType('login')}
                        sx={{ ml: 1 }}
                      >
                        立即登录
                      </Button>
                    </Typography>
                  </Stack>
                  

                </>
              )}
            </Box>
          </Grid>
        </Grid>
      </Paper>
    </Box>
  );
};

export default AuthPage;